package com.example.yyrecorder;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
	
	//检测摇动相关变量
	private long initTime = 0 ;
	private long lastTime = 0 ;
	private long curTime = 0 ;
	private long duration = 0 ;

	private float last_x = 0.0f;
	private float last_y = 0.0f;
	private float last_z = 0.0f;

	private float shake = 0.0f;
	private float totalShake = 0.0f;
	
	private boolean isRecording = false ;
	
	private Button mStartButton;
	private Button mStopButton;
	private TextView mShowText;
	
	private Sensor acceleromererSensor;	
	private MediaRecorder mRecorder = new MediaRecorder();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		acceleromererSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
	
		mStartButton = (Button)findViewById(R.id.main_start_recorder_button);
		mStopButton = (Button)findViewById(R.id.main_stop_recorder_button);
		mShowText = (TextView)findViewById(R.id.main_show_textview);
		
		mStartButton.setOnClickListener(this);
		mStopButton.setOnClickListener(this);
		
		
		SensorEventListener listener = new SensorEventListener(){

			@Override
			public void onSensorChanged(SensorEvent event) {
				// TODO Auto-generated method stub
				
				if(!isRecording){
					
					float x = event.values[SensorManager.DATA_X];
					float y = event.values[SensorManager.DATA_Y];
					float z = event.values[SensorManager.DATA_Z];
					
					curTime = System.currentTimeMillis();

					//100毫秒检测一次
					if ((curTime - lastTime) > 100 ) {

					    duration = (curTime - lastTime);

					    // 看是不是刚开始晃动
					    if (last_x == 0.0f && last_y == 0.0f && last_z == 0.0f) {
					        //last_x、last_y、last_z同时为0时，表示刚刚开始记录
					        initTime = System.currentTimeMillis();
					    } else {
					        // 单次晃动幅度
					        shake = (Math.abs(x - last_x) + Math.abs(y - last_y) + Math.abs(z - last_z)) / duration * 100 ;
					    }

					    //把每次的晃动幅度相加，得到总体晃动幅度
					    totalShake += shake;

					    // 判断是否为摇动，这是我自己写的标准，不准确，只是用来做教学示例，别误会了^_^
					    if (totalShake > 10 && totalShake / (curTime - initTime) * 1000 > 10 ) {
					        startRecord();
					        initShake();
					    }

					    mShowText.setText( "总体晃动幅度=" +totalShake+ "/n平均晃动幅度=" +totalShake / (curTime - initTime) * 1000 );
					}

					last_x = x;
					last_y = y;
					last_z = z;
					lastTime = curTime;
				}
			}

			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) {
				// TODO Auto-generated method stub
				
			}
		};
		
		sm.registerListener(listener, acceleromererSensor, SensorManager.SENSOR_DELAY_NORMAL);
	}
	
	public void initShake() {
	  
		lastTime = 0 ;
	    duration = 0 ;
	    curTime = 0 ;
	    initTime = 0 ;
	    last_x = 0.0f;
	    last_y = 0.0f;
	    last_z = 0.0f;
	    shake = 0.0f;
	    totalShake = 0.0f;
	}
	
	private void initMediaRecorder(){
		
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		mRecorder.setAudioChannels(2);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
		mRecorder.setAudioSamplingRate(44100);
		mRecorder.setOutputFile(
				Environment.getExternalStorageDirectory().getPath() 
				+"/audio.mp4");	
	}
	
	public void  startRecord(){
		
		isRecording = true;
		initMediaRecorder();
		
		try {
			mRecorder.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mRecorder.start();
		
		Toast.makeText(MainActivity.this, "Start Recorder", Toast.LENGTH_LONG).show();
	}
	
	public void stopRecord(){

		mRecorder.stop();
		mRecorder.release();
		isRecording = false;
		
		Toast.makeText(MainActivity.this, "Stop Recorder", Toast.LENGTH_LONG).show();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		int key = v.getId();
		switch (key) {
		case R.id.main_start_recorder_button:
			
			if(!isRecording){
				startRecord();
			}
			
			break;
			
		case R.id.main_stop_recorder_button:
			
			stopRecord();
			break;

		default:
			break;
		}
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
